// pages/accountDetail/accountDetail.js
Page({
  data: {
    id:null,
    balance:0,
    accountDetails:[]
  },
  onLoad(options) {
    this.setData({
      id: options.id
    })
    this.loadAccountDetail(options.id)
  },
  //加载交易明细
  loadAccountDetail:function(accountId){
      var that = this;
      wx.cloud.callFunction({
        name:'loadAccountDetail',
        data:{
          accountId:accountId
        },
        success:res=>{
          console.log('获取成功')
          var result = res.result.data
          // 计算余额
          let balance = 0;
          result.forEach(item => {
            if(item.type === 0) { // 收入
              balance += item.amount
            } else if(item.type === 1) { // 支出
              balance -= item.amount
            }
          })
          this.updata(balance,accountId)
          this.setData({
            accountDetails: result,
            balance: balance
          })
        },
        fail:res=>console.error(res)
      })
  },
  // 更新数据
  updata:function(balance,accountId){
    console.log('当前余额：',balance)
    wx.cloud.callFunction({
      name:'loadAccount',
      data:{
        accountId: accountId
      },
      success(res){
        let accountbalance = res.result.data[0].balance
        console.log('账户余额：',accountbalance)

        if(String(accountbalance) === String(balance)){
          console.log("无需更新~")
          return
        }
        
        wx.cloud.callFunction({
          name:'updataAccount',
          data:{
            accountId: accountId,
            balance: balance,
            after: 0
          },
          success(res){
            console.log('更新成功！',res)
          }
        })
      }
    })
  },
  // 记一笔
  writeOne:function(){
    wx.navigateTo({
      url: `../writeOne/writeOne?id=`+this.data.id
    });
  }
})